package com.gyh.system.log.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Invocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.gyh.system.common.utils.SpringContextHolder;
import com.gyh.system.log.entity.Operation;
import com.gyh.system.log.service.OperationService;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.Manufacturer;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;

/**
* @author 作者 gyh:
* @version 创建时间：2018年1月8日 下午11:24:09
* 
*/
public class OperationRunnable implements Runnable{
	private final Logger log =  LoggerFactory.getLogger(getClass());
	private OperationService operationService = SpringContextHolder.getBean(OperationService.class);
	private HttpServletRequest request;
	private Operation oper = null;
	private Invocation invocation;
	
	public OperationRunnable(Invocation invocation,HttpServletRequest request) {
		this.request = request;
		this.invocation = invocation;
		oper = new Operation();
	}



	@Override
	public void run() {
		
		Object[] args = invocation.getArgs();
		MappedStatement ms= (MappedStatement) args[0];
		BoundSql bounSql = ms.getBoundSql(args[1]);
		String sql = bounSql.getSql();
		oper.setSql(sql);
		
		oper.setIp(request.getRemoteAddr());
		//浏览器的名字
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
		Browser browser = userAgent.getBrowser();
		Manufacturer manufacturer = browser.getManufacturer();
		oper.setBrowser(manufacturer.name());
		//客户端的操作系统 
		OperatingSystem system=userAgent.getOperatingSystem();
		String operasystem=system.getName();
		oper.setSystem(operasystem);
		operationService.insert(oper);
	}

}
